package top.infopub.mgr.cap.web;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import top.infopub.dto.mkt.LoanContractDto;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.LoanContractService;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.model.cap.ResultModel;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.model.cap.*;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author Warking
 * @Date 2021/5/24 9:40
 * @Version 1.0 借款合同
 */
@Controller
@RequestMapping("/loanContract")
public class LoanContractController {
    @Autowired
    private LoanContractService loanContractService;
    @Autowired
    private OAFlowService oaFlowService;
    @Autowired
    private CapProcessManageService capProcessManageService;

    /**
     * 调用http接口
     *
     * @return 返回集合，没有返回空List
     */
    @RequestMapping("/LPR")
    @ResponseBody
    public ResultModel chong() {
        String url = "http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/currency/bk-lpr.json";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity requestBody = new HttpEntity(headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestBody, String.class);
        String result = responseEntity.getBody();
        ResultModel resultModel = JSON.parseObject(result, ResultModel.class);
        return resultModel;
    }

    //跳转详情
    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String id, String proCode) {
        request.setAttribute("proCode", proCode);
        request.setAttribute("id", id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        if (!StringUtils.isEmpty(id)) {
            LoanContract loanContract = loanContractService.findById(id);
            if (loanContract != null) {
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), loanContract.getProcessStatus())
                        || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), loanContract.getProcessStatus())) {
                    request.setAttribute("isAuditFlag", "0");
                }
                if (StringUtils.isNotBlank(loanContract.getProcessId()) && loanContract.getProcessId().length() > 10) {
                    request.setAttribute("processId", loanContract.getProcessId());
                    String auditTabFlag = capProcessManageService.checkShowAuditTab(loanContract.getProcessId(), vo);
                    if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), loanContract.getProcessStatus())
                            && StringUtils.equals("0", auditTabFlag)) {
                        request.setAttribute("isAuditFlag", "0");
                    }
                    request.setAttribute("auditTabFlag", auditTabFlag);
                }
            }
        }
        return "cap/lay-LoanContract-detail";
    }

    //项目下拉接口  从金融机构选择 查询
    @RequestMapping("/selectProCode")
    @ResponseBody
    public List<Map<String, String>> selectProCode() {
        return loanContractService.selectProCode();
    }

    //返回是金融机构选择的主表的ID 去金融机构选择查询主键ID  然后去从金融机构选择找到符合的数据 拿到金融的SGUID去查询出数据和拟题授信金额
    @RequestMapping("/selectOrganization")
    @ResponseBody
    public LoanContractDto selectOrganization(String id) {
        LoanContractDto dto = new LoanContractDto();
        LoanContract loanContract = new LoanContract();
        List<SetupFinancial> setupFinancialList = loanContractService.selectOrganization(id);
        //取出主表数据
        SetupFinancial setup = setupFinancialList.get(0);
        loanContract.setProCode(setup.getProCode());
        loanContract.setProName(setup.getProName());
        loanContract.setLeader(setup.getLeader());
        loanContract.setCapType(setup.getCapType());
        loanContract.setBailMode(setup.getBailMode());
        loanContract.setSgCoopId(setup.getSgCoopId());
        //封装
        dto.setLoanContract(loanContract);
        //
        List<LoanContractDetail> detailArrayList = new ArrayList<>();
        for (int i = 0; i < setupFinancialList.size(); i++) {
            LoanContractDetail detail = new LoanContractDetail();
            detail.setLoanContractSublist(new LoanContractSublist());
            detail.setSetupFinancial(setupFinancialList.get(i));
            detailArrayList.add(detail);
        }
        dto.setLoanContractDetailList(detailArrayList);
        return dto;
    }

    /*借款合同列表接口*/
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<LoanContract> queryDataByCondition(LoanContract loanContract, ParamPage paramPage) throws ParseException {
        Page<LoanContract> page = new Page();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //处理时间范围
        if (!StringUtils.isEmpty(loanContract.getDates())) {
            String[] splitTime = loanContract.getDates().split("~");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            loanContract.setStartDate(format.parse(splitTime[0]));
            loanContract.setEndDate(format.parse(splitTime[1]));
        }
        page = loanContractService.selectPage(page, loanContract);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /*借款合同详情  id是列表带过的 */
    @RequestMapping("/queryDetail")
    @ResponseBody
    public LoanContractDto queryDetail(String id) {
        LoanContractDto loanContractDto = loanContractService.queryDetail(id);
        return loanContractDto;
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //立项审批
        capProcessManageService.auditProject(id, processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }


    //借款合同 保存提交 前端传一个融资的数据过来
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(String loanContractDto, String identifying, String proCode, String id) {
        if (StringUtils.isEmpty(loanContractDto)) {
            return RspVo.getFailureResponse(0, "数据为空");
        }
        String object = StringEscapeUtils.unescapeJava(loanContractDto);
        LoanContractDto dto = JSON.parseObject(object, LoanContractDto.class);
        if ("0".equals(identifying)) {//0是保存
            String SGUID = loanContractService.save(dto, proCode);
            //看数据库是否已经存在这个项目名称
            if ("true".equals(SGUID))
            {
                return RspVo.getFailureResponse(0, "保存失败,该项目已存在");
            }
            if (SGUID!=null && SGUID!="") {
                return RspVo.getSuccessResponse(0, "保存成功");
            } else {
                return RspVo.getFailureResponse(0, "保存失败");
            }
        } else {
            //提交流程  先保存
            String SGUID = loanContractService.save(dto, proCode);
            //看数据库是否已经存在这个项目名称
            if ("true".equals(SGUID))
            {
                return RspVo.getFailureResponse(0, "保存失败,该项目已存在");
            }
            if (StringUtils.isEmpty(id))
            {
                id = SGUID;
            }
            //1是提交
            LoanContract loanContract = loanContractService.findById(id);

            if ("1".equals(loanContract.getProcessStatus()) || "9".equals(loanContract.getProcessStatus())) {
                return RspVo.getFailureResponse(0, "审批中或审批已完成，修改失败");
            }

            if (StringUtils.isNotBlank(loanContract.getOaId())) {
                oaFlowService.finishOA(loanContract.getOaId());
            }

            if (SGUID!=null && SGUID!="") {//保存成的情况 走流程
                //登录人员信息
                AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
                //发起流程
                String process = capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE9, object, id, proCode, vo);
                if (!StringUtils.isEmpty(process)) {
                    return RspVo.getSuccessResponse(0, "提交成功");
                }
                return RspVo.getFailureResponse(0, "提交失败");
            } else { //提交-保存失败
                return RspVo.getFailureResponse(0, "提交失败");
            }

        }
    }

}
